<template>
  <div>
    <!-- 查询框 -->
    <el-row style="margin-left: -55px">
      <el-col :span="20">
        <el-input
          placeholder="请输入内容"
          v-model="select_value"
          style="background-color: #fff; width: 60%"
        >
          <el-select
            v-model="select_key"
            slot="prepend"
            placeholder="查询类型"
            style="width: 130px"
          >
            <el-option label="电话" value="user_tel"></el-option>
            <el-option label="姓名" value="user_name"></el-option>
            <el-option label="角色" value="role_name"></el-option>
          </el-select>
          <el-button
            slot="append"
            icon="el-icon-search"
            @click="selectByPrimaryKey()"
            >查询</el-button
          >
        </el-input>
        <el-button
          style="vertical-align: middle; margin-left: 20px"
          type="success"
          icon="el-icon-plus"
          @click="addOneUser()"
          >添加</el-button
        >
        <el-button
          style="vertical-align: middle; margin-left: 20px"
          icon="el-icon-delete"
          type="danger"
          @click="delAllUsers()"
          >批量删除</el-button
        >
      </el-col>
    </el-row>

    <!-- 员工列表 -->
    <el-row style="margin-top: 15px">
      <el-card shadow="hover">
        <!-- 卡片头部 -->
        <div slot="header" class="clearfix">
          <el-row style="height: 40px">
            <el-col :span="16">
              <div
                style="
                  font-size: 20px;
                  text-align: left;
                  color: #000000;
                  margin: 10px 0px 0px 10px;
                "
              >
                员工列表
              </div>
            </el-col>
          </el-row>
        </div>

        <!-- 列表 -->
        <el-table
          ref="UsersListTable"
          :data="pageInfo.list"
          highlight-current-row
          stripe
          border
          @current-change="handleCurrentChange"
          @selection-change="handleSelectionChange"
          style="width: 100%"
        >
          <el-table-column
            type="selection"
            width="55"
            align="center"
            property="user_id"
          >
          </el-table-column>
          <el-table-column
            property="user_code"
            label="员工编码"
            align="center"
            width="85"
          ></el-table-column>
          <el-table-column
            property="user_name"
            label="姓名"
            align="center"
            width="100"
          ></el-table-column>
          <el-table-column
            property="user_tel"
            label="电话"
            align="center"
            width="130"
          ></el-table-column>
          <el-table-column label="性别" align="center" width="70">
            <div slot-scope="scope">
              <span v-if="scope.row.user_sex == 0">LGBT</span>
              <span v-if="scope.row.user_sex == 1">女</span>
              <span v-if="scope.row.user_sex == 2">男</span>
            </div>
          </el-table-column>
          <el-table-column
            property="user_bir"
            label="生日"
            align="center"
            :formatter="dateCharge"
            width="120"
          ></el-table-column>
          <el-table-column
            property="role.role_name"
            label="职位"
            align="center"
            width="100"
          ></el-table-column>
          <el-table-column
            property="user_status"
            label="状态"
            width="100"
            :filters="[
              { text: '在职', value: 1 },
              { text: '离职', value: 0 },
              { text: '停职', value: 2 },
            ]"
            :filter-method="filterTag"
            filter-placement="bottom-end"
            align="center"
          >
            <template slot-scope="scope">
              <el-tag
                type="success"
                disable-transitions
                v-if="scope.row.user_status == 1"
                >在职</el-tag
              >
              <el-tag
                type="danger"
                disable-transitions
                v-if="scope.row.user_status == 0"
                >离职</el-tag
              >
              <el-tag
                type="warning"
                disable-transitions
                v-if="scope.row.user_status == 2"
                >停职</el-tag
              >
            </template>
          </el-table-column>

          <el-table-column label="操作" align="center">
            <template slot-scope="scope">
              <el-button
                v-if="scope.row.user_status != 0"
                @click="updateUser(scope.row)"
                icon="el-icon-edit"
                size="small"
                type="success"
                circle=""
                
                ></el-button
              >
              <el-button
                v-if="scope.row.user_status != 0"
                @click="updateUserStatus(scope.row)"
                icon="el-icon-delete"
                size="small"
                type="danger"
                circle=""
                ></el-button
              >
              <el-button
                v-if="scope.row.user_status == 1"
                @click="giveRole(scope.row)"
                icon="el-icon-edit"
                size="small"
                type="warning"
                >更换职位</el-button
              >
              <el-button
                @click="resetPwd(scope.row)"
                icon="el-icon-refresh-right"
                size="small"
                type="success"
                >重置密码</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </el-row>

    <!-- 分页 -->
    <el-row>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentPageChange"
        :current-page="pageInfo.pageNum"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="pageInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pageInfo.total"
      ></el-pagination>
    </el-row>
    <!-- 添加用户弹出框 -->
    <el-dialog :visible.sync="addUserDialogVisible" title="添加新员工">
      <!-- 添加用户表单 -->
      <el-form
        :model="addUser"
        :rules="rules"
        ref="addUserDialog"
        label-width="100px"
      >
        <el-form-item label="姓名" prop="user_name">
          <el-input type="text" v-model="addUser.user_name"></el-input>
        </el-form-item>
        <el-form-item label="员工编码" prop="user_code">
          <el-input type="text" v-model="addUser.user_code"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="user_tel">
          <el-input type="text" v-model="addUser.user_tel"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="user_sex">
          <el-radio-group v-model="addUser.user_sex">
            <el-radio :label="1">女</el-radio>
            <el-radio :label="2">男</el-radio>
            <el-radio :label="0">LGBT</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="生日" prop="user_bir">
          <el-date-picker
            v-model="addUser.user_bir"
            type="date"
            placeholder="选择日期"
            format="yyyy 年 MM 月 dd 日"
            value-format="yyyy-MM-dd"
            :picker-options="beforeToday"
            :editable="false"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="职位" prop="role_id">
          <el-select v-model="addUser.role_id" clearable placeholder="请选择">
            <el-option
              v-for="role in roleList"
              :key="role.role_id"
              :label="role.role_name"
              :value="role.role_id"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <!-- 提交表单按钮 -->
        <el-form-item>
          <el-row id="centerBtnAdd">
            <el-button type="success" @click="saveUser('addUserDialog')"
              >保存</el-button
            >
            <el-button type="primary" @click="resetAddUser('addUserDialog')"
              >重置</el-button
            >
          </el-row>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 添加用户弹出框结束-->

    <!-- 编辑用户弹出框 -->
    <el-dialog :visible.sync="updUserDialogVisible" title="修改员工">
      <!-- 修改用户表单 -->
      <el-form
        :model="updUser"
        :rules="rules"
        ref="updUserDialog"
        label-width="100px"
      >
        <el-form-item label="姓名" prop="user_name">
          <el-input type="text" v-model="updUser.user_name"></el-input>
        </el-form-item>
        <el-form-item label="员工编码" prop="user_code">
          <el-input type="text" v-model="updUser.user_code"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="user_tel">
          <el-input type="text" v-model="updUser.user_tel"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="user_sex">
          <el-radio-group v-model="updUser.user_sex">
            <el-radio :label="1">女</el-radio>
            <el-radio :label="2">男</el-radio>
            <el-radio :label="0">LGBT</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="生日" prop="user_bir">
          <el-date-picker
            v-model="updUser.user_bir"
            type="date"
            placeholder="选择日期"
            format="yyyy 年 MM 月 dd 日"
            value-format="yyyy-MM-dd"
            :picker-options="beforeToday"
            :editable="false"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="职位" prop="role_id">
          <el-select v-model="updUser.role_id" clearable placeholder="请选择">
            <el-option
              v-for="role in roleList"
              :key="role.role_id"
              :label="role.role_name"
              :value="role.role_id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="user_status">
          <el-radio-group v-model="updUser.user_status">
            <el-radio :label="1">在职</el-radio>
            <el-radio :label="2">停职</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 提交表单按钮 -->
        <el-form-item>
          <el-row id="centerBtnUpd">
            <el-button type="success" @click="saveUpdUser('updUserDialog')"
              >保存</el-button
            >
            <el-button type="primary" @click="resetUpdUser('updUserDialog')"
              >重置</el-button
            >
          </el-row>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 编辑用户弹出框结束-->

    <!-- 分配角色对话框开始 -->
    <el-dialog
      title="更换职位"
      :visible.sync="centerDialogVisible"
      width="50%"
      center
    >
      <div style="margin-top: 20px">
        <el-radio-group v-model="changeRoleId" size="medium">
          <!-- 此处label是选中的值 -->
          <el-radio-button
            v-for="role in roleList"
            :label="role.role_id"
            :key="role.role_id"
            style="
              margin: 0 10px;
              border: 1px solid darkgray;
              border-radius: 4px;
            "
            >{{ role.role_name }}</el-radio-button
          >
        </el-radio-group>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="centerDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveChangeRole()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色对话框结束 -->
  </div>
</template>
<script>
import {md5} from "../MD5"
export default {
  data() {
    return {
      //所有用户存在pageinfo的list中
      pageInfo: {},

      //当前页，默认第一页
      currentPage: 1,

      //每页显示条目数，默认5条
      pageSize: 5,

      // 查询类型和值
      select_value: "",
      select_key: "",

      //当前行
      currentRow: "",

      //多选框选中行id
      multipleSelection: [],

      //全部角色
      roleList: [],

      //新添员工对话框显示属性
      addUserDialogVisible: false,

      //新添的员工
      addUser: {
        user_name: "",
        user_tel: "",
        user_sex: 1,
        user_bir: "",
        role_id: "",
        user_code: "",
      },

      //修改员工对话框显示属性
      updUserDialogVisible: false,

      //修改的员工
      updUser: {
        user_id: "",
        user_name: "",
        user_tel: "",
        user_sex: "",
        user_bir: "",
        role_id: "",
        user_status: "",
        user_code: "",
      },
      //更换职位对话框显示属性
      centerDialogVisible: false,
      //更换职位的用户信息
      changeRoleId: "",
      changeRole: {},

      //只能选择今天及之前的日期
      beforeToday: {
        disabledDate(time) {
          //alert("@@@@@@@@");
          return time.getTime() > Date.now() - 8.64e6;
        },
      },

      //表单验证规则
      rules: {
        user_status: [
          { required: true, message: "请选择状态", trigger: "change" },
        ],
        user_name: [
          { required: true, message: "请填写姓名", trigger: "blur" },
          {
            pattern: /^[\u4e00-\u9fa5]{2,50}$/,
            message: "姓名为2～50个汉字，不能有字母、数字、特殊字符或空格",
            trigger: "blur",
          },
        ],
        user_tel: [
          { required: true, message: "请填写电话", trigger: "blur" },
          { len: 11, message: "必须是11位的数字", trigger: "blur" },
          {
            pattern: /^[1][3,4,5,7,8,9]\d{9}$/,
            message: "电话号码为13、14、15、17、18、19开头",
            trigger: "blur",
          },
        ],
        user_sex: [
          { required: true, message: "请选择性别", trigger: "change" },
        ],
        user_bir: [
          { required: true, message: "请选择生日", trigger: "change" },
        ],
        role_id: [{ required: true, message: "请选择职位", trigger: "change" }],
        user_code: [
          { required: true, message: "请填写员工编码", trigger: "blur" },
          { max: 5, message: "编码最多5位", trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    //加载员工列表
    loadUsers() {
      if (this.select_key == "" && this.select_value != "") {
        this.$message({
          type: "warning",
          message: "请选择查询类型!",
        });
      } else {
        this.$axios
          .get("/users/key", {
            params: {
              currentPage: this.currentPage,
              pageSize: this.pageSize,
              key: this.select_key,
              value: this.select_value,
            },
          })
          .then((resp) => {
            if (resp.data.status == 1000) {
              this.pageInfo = resp.data.data;
              // alert(this.userList)
            } else {
              this.$message({
                type: "error",
                message: "暂无相应数据!",
              });
            }
          })
          .catch((error) => {});
      }
    },

    //改变分页条目数val：每页的条目数
    handleSizeChange(val) {
      //alert(val);
      this.pageSize = val;
      this.currentPage = 1;
      this.loadUsers();
      //console.log(`每页 ${val} 条`);
    },

    //当前显示第几页val:当前页
    handleCurrentPageChange(val) {
      //alert(val);
      this.currentPage = val;
      this.loadUsers();
      //console.log(`当前页: ${val}`);
    },

    // 查询框-------------------------------------------------------
    selectByPrimaryKey() {
      this.loadUsers();
    },

    // 表格控制当前选中行
    handleCurrentChange(val) {
      this.currentRow = val;
    },

    // 表格中的“状态”过滤器
    filterTag(value, row) {
      return row.user_status === value;
    },

    //表格中已选中的多选框
    handleSelectionChange(val) {
      let ids = [];
      for (let user of val) {
        ids.push(user.user_id);
      }
      this.multipleSelection = ids;
    },

    //表格中日期展示变换
    dateCharge(row, column) {
      let datetime = row.user_bir;
      if (datetime) {
        datetime = new Date(datetime);
        let y = datetime.getFullYear() + "-";
        let mon = datetime.getMonth() + 1 + "-";
        let d = datetime.getDate();
        return y + mon + d;
      }
      return "";
    },

    //查询所有角色
    loadAllRoles() {
      this.$axios
        .get("/roles/all")
        .then((resp) => {
          this.roleList = resp.data.data;
        })
        .catch((error) => {});
    },

    //点击新添员工按钮
    addOneUser() {
      this.loadAllRoles();
      this.addUserDialogVisible = true;
    },

    //重置密码resetPwd
    resetPwd(user){
      this.$confirm("确定重置密码吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          //  确认是重置密码为123456
          user.user_password = md5("123456");
          this.$axios
            .put("/users", user)
            .then((resp) => {
              if ((resp.data.status = 1000)) {
                this.$message({
                  type: "success",
                  message: "重置密码成功!",
                });
                this.loadUsers();
              } else {
                this.$message({
                  type: "error",
                  message: "重置密码失败!",
                });
              }
            })
            .catch((error) => {});
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    //保存新添员工
    saveUser(addUserDialog) {
      //console.log(this.addUser);

      this.$refs[addUserDialog].validate((valid) => {
        if (valid) {
          this.$axios
            .post("/users", this.addUser)
            .then((resp) => {
              if (resp.data.status == 1000) {
                //alert(resp.data.message);
                this.$message({
                  type: "success",
                  message: "保存成功!",
                });
                this.addUserDialogVisible = false;
                this.$refs[addUserDialog].resetFields();
                this.loadUsers();
              } else if (resp.data.status == 1001) {
                //alert(resp.data.message);
                this.$message({
                  type: "error",
                  message: "保存失败!",
                });
              } else if (resp.data.status == 1002) {
                //alert(resp.data.message);
                this.$message({
                  type: "error",
                  message: "保存失败!员工编码不能重复!",
                });
              }
            })
            .catch((error) => {});
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },

    //重置新添员工
    resetAddUser(addUserDialog) {
      this.$refs[addUserDialog].resetFields();
    },
    //点击编辑员工按钮
    updateUser(user) {
      console.log(user.user_id);
      this.loadAllRoles();
      this.$axios
        .get("/users/" + user.user_id)
        .then((resp) => {
          if (resp.data.status == 1000) {
            this.updUser = resp.data.data;
          } else {
            console.log("修改时查询修改员工失败");
          }
        })
        .catch((error) => {});
      this.updUserDialogVisible = true;
    },

    //保存修改员工
    saveUpdUser(updUserDialog) {
      console.log(this.updUser);
      this.$refs[updUserDialog].validate((valid) => {
        if (valid) {
          this.$axios
            .put("/users", this.updUser)
            .then((resp) => {
              if (resp.data.status == 1000) {
                //alert(resp.data.message);
                this.$message({
                  type: "success",
                  message: "保存成功!",
                });
                this.updUserDialogVisible = false;
                this.$refs[updUserDialog].resetFields();
                this.loadUsers();
              } else if (resp.data.status == 1001) {
                //alert(resp.data.message);
                this.$message({
                  type: "error",
                  message: "保存失败!",
                });
              } else if (resp.data.status == 1002) {
                //alert(resp.data.message);
                this.$message({
                  type: "error",
                  message: "保存失败!员工编码不能重复!",
                });
              }
            })
            .catch((error) => {});
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },

    //重置修改员工
    resetUpdUser(updUserDialog) {
      //alert("######");
      this.updateUser(this.updUser);
    },

    //删除员工
    updateUserStatus(user) {
      this.$confirm("确定删除该用户吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          //  确认删除时修改员工状态为0（离职）
          user.user_status = 0;
          this.$axios
            .put("/users", user)
            .then((resp) => {
              if ((resp.data.status = 1000)) {
                this.$message({
                  type: "success",
                  message: "该员工已确认离职!",
                });
                this.loadUsers();
              } else {
                this.$message({
                  type: "error",
                  message: "删除失败!",
                });
              }
            })
            .catch((error) => {});
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    //批量删除
    delAllUsers() {
      //alert(this.multipleSelection)
      if (this.multipleSelection.length == 0) {
        this.$message({
          message: "请至少选择一项",
          type: "warning",
        });
      } else {
        this.$confirm("确认删除吗?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            this.$axios
              .post("/users/deletelist", this.multipleSelection)
              .then((resp) => {
                if (resp.data.status == 1000) {
                  this.$message({
                    message: "这些员工已确认离职",
                    type: "success",
                  });
                  this.loadUsers();
                } else {
                  this.$message({
                    message: "批量删除失败",
                    type: "error",
                  });
                }
              })
              .catch((error) => {});
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消删除",
            });
          });
      }
    },

    //分配角色/职位
    giveRole(user) {
      this.changeRole = user;
      this.loadAllRoles();
      this.changeRoleId = user.role_id;
      //alert(this.changeRoleId);
      this.centerDialogVisible = true;
    },

    //保存角色/职位
    saveChangeRole() {
      this.changeRole.role_id = this.changeRoleId;
      //alert(this.changeRole);
      this.$axios.put("/users", this.changeRole).then((resp) => {
        if (resp.data.status == 1000) {
          this.centerDialogVisible = false;
          this.$message({
            type: "success",
            message: "保存成功!",
          });
          this.loadUsers();
        }
      });
    },
  },

  mounted() {
    this.loadUsers();
  },
};
</script>
<style >
.el-dialog {
  width: 35%;
}
.el-form-item__content {
  text-align: left;
}

#centerBtnAdd,
#centerBtnUpd {
  margin-left: 75px;
}
</style>